package com.micro.ai.agents.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.micro.ai.commons.exception.BusinessException;
import com.micro.ai.agents.entity.AgentFineTunedModelMapping;
import com.micro.ai.agents.mapper.AgentFineTunedModelMappingMapper;
import com.micro.ai.agents.service.AgentFineTunedModelMappingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 智能体-微调模型关联服务实现
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@Service
public class AgentFineTunedModelMappingServiceImpl extends ServiceImpl<AgentFineTunedModelMappingMapper, AgentFineTunedModelMapping> implements AgentFineTunedModelMappingService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AgentFineTunedModelMapping create(AgentFineTunedModelMapping mapping) {
        if (mapping == null) {
            throw new BusinessException("A0000", "关联信息不能为空");
        }
        
        if (!StringUtils.hasText(mapping.getAgentId())) {
            throw new BusinessException("A0000", "智能体ID不能为空");
        }
        
        if (!StringUtils.hasText(mapping.getFineTunedModelId())) {
            throw new BusinessException("A0000", "微调模型ID不能为空");
        }
        
        // 检查关联是否已存在
        LambdaQueryWrapper<AgentFineTunedModelMapping> query = new LambdaQueryWrapper<>();
        query.eq(AgentFineTunedModelMapping::getAgentId, mapping.getAgentId())
             .eq(AgentFineTunedModelMapping::getFineTunedModelId, mapping.getFineTunedModelId());
        
        AgentFineTunedModelMapping existing = this.getOne(query);
        if (existing != null) {
            throw new BusinessException("A0001", "该微调模型已关联到此智能体");
        }
        
        if (mapping.getPriority() == null) {
            mapping.setPriority(1);
        }
        if (mapping.getIsActive() == null) {
            mapping.setIsActive(true);
        }
        if (mapping.getTotalRequests() == null) {
            mapping.setTotalRequests(0);
        }
        if (mapping.getSuccessRequests() == null) {
            mapping.setSuccessRequests(0);
        }
        if (mapping.getAvgResponseTimeMs() == null) {
            mapping.setAvgResponseTimeMs(0);
        }
        
        LocalDateTime now = LocalDateTime.now();
        mapping.setCreatedAt(now);
        mapping.setUpdatedAt(now);
        
        boolean success = this.save(mapping);
        if (!success) {
            throw new BusinessException("A0003", "保存关联失败");
        }
        
        log.info("创建智能体-微调模型关联成功: mappingId={}, agentId={}, modelId={}", 
                mapping.getId(), mapping.getAgentId(), mapping.getFineTunedModelId());
        return mapping;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AgentFineTunedModelMapping update(String id, AgentFineTunedModelMapping mapping) {
        if (!StringUtils.hasText(id)) {
            throw new BusinessException("A0000", "关联ID不能为空");
        }
        if (mapping == null) {
            throw new BusinessException("A0000", "关联信息不能为空");
        }
        
        AgentFineTunedModelMapping existing = this.getById(id);
        if (existing == null) {
            throw new BusinessException("A0002", "关联不存在: " + id);
        }
        
        mapping.setId(id);
        mapping.setUpdatedAt(LocalDateTime.now());
        
        boolean success = this.updateById(mapping);
        if (!success) {
            throw new BusinessException("A0003", "更新关联失败");
        }
        
        log.info("更新智能体-微调模型关联成功: mappingId={}", id);
        return mapping;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String id) {
        if (!StringUtils.hasText(id)) {
            throw new BusinessException("A0000", "关联ID不能为空");
        }
        
        AgentFineTunedModelMapping mapping = this.getById(id);
        if (mapping == null) {
            throw new BusinessException("A0002", "关联不存在: " + id);
        }
        
        boolean success = this.removeById(id);
        if (!success) {
            throw new BusinessException("A0003", "删除关联失败");
        }
        
        log.info("删除智能体-微调模型关联成功: mappingId={}", id);
    }

    @Override
    public List<AgentFineTunedModelMapping> listByAgentId(String agentId) {
        LambdaQueryWrapper<AgentFineTunedModelMapping> query = new LambdaQueryWrapper<>();
        query.eq(AgentFineTunedModelMapping::getAgentId, agentId)
             .eq(AgentFineTunedModelMapping::getIsActive, true)
             .orderByAsc(AgentFineTunedModelMapping::getPriority);
        
        return this.list(query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatistics(String id, boolean success, Integer responseTimeMs) {
        AgentFineTunedModelMapping mapping = this.getById(id);
        if (mapping == null) {
            throw new BusinessException("A0002", "关联不存在: " + id);
        }
        
        // 更新统计数据
        int totalRequests = (mapping.getTotalRequests() != null ? mapping.getTotalRequests() : 0) + 1;
        int successRequests = (mapping.getSuccessRequests() != null ? mapping.getSuccessRequests() : 0);
        if (success) {
            successRequests++;
        }
        
        // 计算平均响应时间
        int currentAvg = mapping.getAvgResponseTimeMs() != null ? mapping.getAvgResponseTimeMs() : 0;
        int newAvg;
        if (responseTimeMs != null && responseTimeMs > 0) {
            if (totalRequests == 1) {
                newAvg = responseTimeMs;
            } else {
                newAvg = (currentAvg * (totalRequests - 1) + responseTimeMs) / totalRequests;
            }
        } else {
            newAvg = currentAvg;
        }
        
        mapping.setTotalRequests(totalRequests);
        mapping.setSuccessRequests(successRequests);
        mapping.setAvgResponseTimeMs(newAvg);
        mapping.setUpdatedAt(LocalDateTime.now());
        
        this.updateById(mapping);
        
        log.debug("更新智能体-微调模型统计成功: mappingId={}, total={}, success={}, avgTime={}", 
                id, totalRequests, successRequests, newAvg);
    }

    @Override
    public Page<AgentFineTunedModelMapping> pageQuery(int pageNum, int pageSize, String tenantId, String agentId) {
        if (pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize < 1 || pageSize > 100) {
            pageSize = 20;
        }
        
        Page<AgentFineTunedModelMapping> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<AgentFineTunedModelMapping> query = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(tenantId)) {
            query.eq(AgentFineTunedModelMapping::getTenantId, tenantId);
        }
        if (StringUtils.hasText(agentId)) {
            query.eq(AgentFineTunedModelMapping::getAgentId, agentId);
        }
        
        query.orderByAsc(AgentFineTunedModelMapping::getPriority)
             .orderByDesc(AgentFineTunedModelMapping::getUpdatedAt);
        
        return this.page(page, query);
    }
}

